package at.fhv.components.threshold;

import java.awt.image.renderable.ParameterBlock;

import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;

import at.fhv.framework.CommonImageProcessingHelper;
import at.fhv.framework.events.ImageEvent;
import at.fhv.framework.listeners.ImageProcessingListener;
import at.fhv.framework.listeners.RefireListener;

/**
 * The ROIFilter class.
 * 
 * @author Michael Sieber
 */
public class ThresholdFilter implements ImageProcessingListener, RefireListener
{
	private CommonImageProcessingHelper	_helper;
	private PlanarImage					_image;
	private double[]					_low;
	private double[]					_high;
	private double[]					_map;

	public ThresholdFilter()
	{
		_helper = new CommonImageProcessingHelper(this);
		_low = new double[] { 10d };
		_high = new double[] { 10d };
		_map = new double[] { 10d };
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public void refire() {
		_helper.fireImageProcessingEvent(new ImageEvent(this, _image));
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public void imageChanged(ImageEvent event) {
		_image = event.getImage();
		execute();
	}

	/**
	 * Execute roi
	 * 
	 * @param image
	 */
	private void execute() {
		if (_image != null)
		{
			ParameterBlock pb = new ParameterBlock();
			pb.addSource(_image);
			pb.add(_low);
			pb.add(_high);
			pb.add(_map);

			_helper.fireImageProcessingEvent(new ImageEvent(this, JAI.create("threshold", pb)));
		}
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public void addRefireListener(RefireListener listener) {
		_helper.addRefireListener(listener);
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public void removeRefireListener(RefireListener listener) {
		_helper.removeRefireListener(listener);
	}

	/**
	 * Add an image change listener
	 * 
	 * @param listener
	 *            The image change listener to add
	 */
	public void addImageChangeListener(ImageProcessingListener listener) {
		_helper.addImageProcessingListener(listener);

		// force all previous beans to refire their event
		_helper.fireRefireEvent();
	}

	/**
	 * Remove an image change listener
	 * 
	 * @param listener
	 *            The image change listener to remove
	 */
	public void removeImageChangeListener(ImageProcessingListener listener) {
		_helper.removeImageProcessingListener(listener);
	}

	public double getLow() {
		return _low[0];
	}

	public void setLow(double low) {
		_helper.fireRefireEvent();
		_low = new double[] { low };
		execute();
	}

	public double getHigh() {
		return _high[0];
	}

	public void setHigh(double high) {
		_helper.fireRefireEvent();
		_high = new double[] { high };
		execute();
	}

	public double getMap() {
		return _map[0];
	}

	public void setMap(double map) {
		_helper.fireRefireEvent();
		_map = new double[] { map };
		execute();
	}
}